package com.example.chatroom.common.component;

import com.example.chatroom.common.utils.JacksonUtil;
import com.example.chatroom.controller.param.WebSocketMessageParam;
import com.example.chatroom.controller.result.WebSocketMessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class OnlineUserManager {
    private ConcurrentHashMap<Long, WebSocketSession> concurrentHashMap=new ConcurrentHashMap<>();

    /**
     * 用户上线 绑定到map
     * @param userId 用户Id
     * @param webSocketSession
     * @return
     */
    public boolean onlineUser(Long userId,WebSocketSession webSocketSession){
        if(userId==null||webSocketSession==null){
            log.error("参数为空 userId:{} webSocketSession:{}",userId,webSocketSession);
            return false;
        }
        log.info("onlineUser userId:{}",userId);
        //判断userId是否已经存在在map中
        if(concurrentHashMap.get(userId)!=null){
            //已存在说明用户多开了
            log.error("应用多开：当前用户已登陆 userId:{}",userId);
            try {
                WebSocketMessageResult webSocketMessageResult=new WebSocketMessageResult();
                webSocketMessageResult.setType("error");
                String s = JacksonUtil.writeValueAsString(webSocketMessageResult);
                webSocketSession.sendMessage(new TextMessage(s));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return false;
        }
        //添加到map中
        concurrentHashMap.put(userId,webSocketSession);
        log.info("用户 userId:{} 上线!",userId);
        return true;
    }

    /**
     * 用户下线
     * @param userId
     * @param webSocketSession
     * @return
     */
    public boolean offLine(Long userId,WebSocketSession webSocketSession){
        if(userId==null||webSocketSession==null){
            log.error("参数为空 userId:{} webSocketSession:{}",userId,webSocketSession);
            return false;
        }
        //判断userId对应的webSocketSession 与参数 webSocketSession 是否相同
        if((WebSocketSession)concurrentHashMap.get(userId)!=webSocketSession){
            log.error("应用多开：无法删除已被登陆用户 userId:{}",userId);
            return false;
        }
        concurrentHashMap.remove(userId);
        return true;
    }

    /**
     * 获取userId对应的Websocketsession
     * @param userId
     * @return
     */
    public WebSocketSession getWebSocketSession(Long userId){
        if(userId==null){
            log.error("参数为空 userId:{} ",userId);
            return null;
        }
        return concurrentHashMap.get(userId);
    }
}
